local dbg = require 'jass.debug'
local jass = require 'jass.common'

local class = { }
setmetatable(class,class)
ac.selector.class['destructable'] = class

local GROUP = { } 

local function ENUM()
	local destructable = ac.destructable.j_destructable(jass.GetEnumDestructable())
	if destructable then 
		table.insert(GROUP, destructable)
	end 
end 

-- 范围选择
class['range'] = function(self,info)
    local p = self._point
    local r = self._range
    local rct = ac.rect(p,r*2,r*2)
	jass.EnumDestructablesInRect(ac.rect.j_temp(rct),nil, ENUM)
    local loop = #GROUP
    while true do
        local u = GROUP[loop]
        if u then
            if (p* u:get_point()) <= r and self:do_filter(u) then 
                table.insert(info,u)
            end
            loop = loop - 1 
        else
            break
        end 
    end
    GROUP = { }
end

-- 矩形选择
class['rect'] = function(self,info)
	jass.EnumDestructablesInRect(ac.rect.j_temp(self._rect),nil, ENUM)
    local loop = #GROUP
    while true do
        local u = GROUP[loop]
        if u then
            if self:do_filter(u) then 
                table.insert(info,u)
            end
            loop = loop - 1 
        else
            break
        end 
    end
    GROUP = { }
end 

local mt = { }
class.__index = mt 
extends(ac.selector)(mt)

-- 选取树木
function mt:is_tree()
    self:filter(function(dest)
        return dest:is_tree()
    end)
    return self
end 

-- 选取墙体
function mt:is_wall()
    self:filter(function(dest)
        return dest:is_wall()
    end)
    return self
end 

function mt:can_dead()
    self._dead = true
    return self
end 

-- 必须是死亡的
function mt:must_dead()
    self:filter(function(dest)
        return not dest:is_alive()
    end)
    return self
end 

-- 选取
function mt:select()
    local name = self._type 
    if name and class[name] then 
        local info = { }
        class[name](self,info)
        return info
    else
        log.error('没有该选取方式',name)
    end 
end

-- 过滤
function mt:do_filter(u)
    if not self._dead and not u:is_alive() then 
        return false 
    end
    return ac.selector.do_filter(self,u)
end 

return class 